<template>
  <div class="app-container">
    <div class="tabInfo">
    <div class="search">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        class="demo-form-inline"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="deployTime">
          <el-date-picker
            clearable
            v-model="queryParams.deployTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索</el-button
          >
          <el-button size="mini" @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置</el-button
          >
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="success" plain size="mini" @click="handleLoadXml">
            <el-icon><Plus /></el-icon>
            新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:deployment:remove']"
          >
            <el-icon><Delete /></el-icon>
            删除</el-button
          >
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>
    </div>

    <div class="table" :style="{ height: tabHeight + 'px' }">
      <el-table
        :height="tabHeight"
        :data="definitionList"
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="流程编号" align="center" prop="deploymentId" />
        <el-table-column
          label="流程标识"
          align="center"
          prop="flowKey"
          :show-overflow-tooltip="true"
        />
        <!-- <el-table-column label="流程分类" align="center" prop="category" /> -->
        <el-table-column
          label="流程名称"
          align="center"
          width="120"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <el-button type="text" @click="handleReadImage(scope.row)">
              {{ scope.row.name }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          label="业务表单"
          align="center"
          :show-overflow-tooltip="true"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.formId"
              type="text"
              @click="handleForm(scope.row.formId)"
            >
              <span>{{ scope.row.formName }}</span>
            </el-button>
            <label v-else>暂无表单</label>
          </template>
        </el-table-column>
        <el-table-column label="流程版本" align="center">
          <template #default="scope">
            <el-tag size="medium">v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.suspensionState === 1"
              >激活</el-tag
            >
            <el-tag type="warning" v-if="scope.row.suspensionState === 2"
              >挂起</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          label="部署时间"
          align="center"
          prop="deploymentTime"
          width="180"
        />
        <el-table-column
          label="操作"
          width="250"
          fixed="right"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              @click="handleLoadXml(scope.row)"
              type="text"
              size="small"
            >
              <el-icon><Document /></el-icon>
              设计</el-button
            >
            <el-button
              @click="handleAddForm(scope.row)"
              type="text"
              size="small"
              v-if="scope.row.formId == null"
            >
              <el-icon><Promotion /></el-icon>
              配置主表单</el-button
            >
            <el-button
              @click="handleUpdateSuspensionState(scope.row)"
              type="text"
              size="small"
              v-if="scope.row.suspensionState === 1"
            >
              <el-icon><VideoPause /></el-icon>
              挂起</el-button
            >
            <el-button
              @click="handleUpdateSuspensionState(scope.row)"
              type="text"
              size="small"
              v-if="scope.row.suspensionState === 2"
            >
              <el-icon><VideoPlay /></el-icon>
              激活</el-button
            >
            <el-button
              @click="handleDelete(scope.row)"
              type="text"
              size="small"
              v-hasPermi="['system:deployment:remove']"
            >
              <el-icon><Delete /></el-icon>
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    </div>
    <!-- 添加或修改流程定义对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="看看" prop="name">
          <el-input v-model="form.name" placeholder="请输入看看" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- bpmn20.xml导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xml"
        :headers="upload.headers"
        :action="
          upload.url + '?name=' + upload.name + '&category=' + upload.category
        "
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          流程名称：<el-input v-model="upload.name" />
          流程分类：
          <div>
            <el-select v-model="upload.category" placeholder="请选择流程分类">
              <el-option
                v-for="dict in sys_process_category"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </div>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“bpmn20.xml”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 流程图 -->
    <el-dialog
      :title="readImage.title"
      v-model="readImage.open"
      width="70%"
      append-to-body
    >
      <!-- <el-image :src="readImage.src"></el-image> -->
      <bpmnViewer :flowData="flowData" />
    </el-dialog>

    <!--表单配置详情-->
    <el-dialog :title="formTitle" v-model="formConfOpen">
      <div class="test-form">
        <v-form-render
          :disabled="disabledForm"
          :form-data="formData"
          ref="vFormRef"
        />
      </div>
    </el-dialog>

    <!--挂载表单-->
    <el-dialog
      :title="formDeployTitle"
      v-model="formDeployOpen"
      width="80%"
      style="height: 80%"
    >
      <el-row :gutter="24">
        <el-col :span="10" :xs="24">
          <el-table
            ref="singleTable"
            :data="formList"
                        highlight-current-row
            @current-change="handleCurrentChange"
            style="width: 100%"
          >
            <el-table-column label="表单编号" align="center" prop="formId" />
            <el-table-column label="表单名称" align="center" prop="formName" />
            <el-table-column
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="submitFormDeploy(scope.row)"
                  >确定</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            class="MountForm"
            v-show="formTotal > 0"
            :total="formTotal"
            v-model:page="formQueryParams.pageNum"
            v-model:limit="formQueryParams.pageSize"
            @pagination="ListFormDeploy"
          />
        </el-col>
        <el-col :span="14" :xs="24">
          <div class="test-form">
            <v-form-render
              :disabled="true"
              :form-data="formData"
              ref="vFormCurrentRowRef"
            />
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script setup>
import { getCommonTableHeight } from "@/utils/commonTableHeight.js";
import { ref, reactive, onMounted, onActivated, defineComponent } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import bpmnViewer from "../../../components/Process/viewer/index.vue";
import {
  listDefinition,
  updateState,
  delDeployment,
  addDeployment,
  updateDeployment,
  exportDeployment,
  definitionStart,
  flowXmlAndNode,
} from "@/api/flowable/definition";

import { getDeployment } from "@/api/flowable/finished";
import { getForm, addDeployForm, listForm } from "@/api/flowable/form";

const route = useRoute();
const router = useRouter();

const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const definitionList = ref([]);
const title = ref("");
const open = ref(false);
const formConfOpen = ref(false);
const formTitle = ref("");
const formDeployOpen = ref(false);
const formDeployTitle = ref("");
const formList = ref([]);
const formTotal = ref(0);
const formData = ref({}); // 默认表单数据

const disabledForm = ref(false);

const readImage = reactive({
  open: false,
  src: "",
});
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  name: null,
  category: null,
  headers: { Authorization: "Bearer " + getToken() },
  // url: process.env.VUE_APP_BASE_API + "/flowable/definition/import"
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  category: null,
  key: null,
  tenantId: null,
  deployTime: null,
  derivedFrom: null,
  derivedFromRoot: null,
  parentDeploymentId: null,
  engineVersion: null,
});

const formQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 挂载表单到流程实例
const formDeployParam = reactive({
  formId: null,
  deployId: null,
});

// sys_process_category     流程分类

const { proxy } = getCurrentInstance();
const { sys_process_category } = proxy.useDict("sys_process_category");

const deployId = ref("");
const currentRow = ref(null);
// xml
const flowData = ref({});
// 表单参数
const form = ref({});
// 表单校验
const rules = ref({});

const vFormCurrentRowRef = ref(null);

const vFormRef = ref(null);
const tabHeight = ref(0);

const updateViewportHeight = () => {
  tabHeight.value = getCommonTableHeight();
};
onMounted(() => {
  updateViewportHeight(); // 初始化视口高度
  window.addEventListener("resize", updateViewportHeight); // 监听窗口大小变化
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", updateViewportHeight); // 移除监听
});

onMounted(() => {
  getList();
});

onActivated(() => {
  const time = route.query.t;
  if (time != null) {
    getList();
  }
});

const getList = () => {
  loading.value = true;
  console.log(queryParams);

  listDefinition(queryParams).then((response) => {
    console.log(response.data.records, "流程列表数据");
    definitionList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 重置按钮
const reset = () => {
  form.value = {
    id: null,
    name: null,
    category: null,
    key: null,
    tenantId: null,
    deployTime: null,
    derivedFrom: null,
    derivedFromRoot: null,
    parentDeploymentId: null,
    engineVersion: null,
  };
  // this.resetForm("form"); // 需要根据具体实现调整
};

// 搜索按钮
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮
const resetQuery = () => {
  // this.resetForm("queryForm"); // 需要根据具体实现调整
  handleQuery();
};

// 多选框选中按钮
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.deploymentId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 跳转到流程设计页面

const handleLoadXml = (row) => {
  router.push({
    path: "/flowable/definition/model",
    query: { deployId: row.deploymentId },
  });
};

// 流程图查看
const handleReadImage = (deployId) => {
  console.log(deployId);
  readImage.title = "流程图";
  readImage.open = true;
  flowXmlAndNode({ deployId: deployId.deploymentId }).then((res) => {
    console.log(res.data, "流程图");
    flowData.value = res.data;
  });
};

// 表单查看
const handleForm = (formId) => {
  getForm(formId).then((res) => {
    formTitle.value = "表单详情";
    formConfOpen.value = true;
    console.log(res.data, "表单详情");

    // 回显数据
    // this.$refs.vFormRef.setFormJson(JSON.parse(res.data.formContent));
    vFormRef.value.setFormJson(
      JSON.parse(JSON.stringify(res.data.formContent))
    );

    disabledForm.value = true;
    // vFormRef.value = JSON.parse(JSON.stringify(res.data.formContent))

    // 表单禁用
    // vFormRef.value.disableForm();
  });
};

const handleDefinitionStart = (row) => {
  definitionStart(row.id).then((res) => {
    ElMessage.success(res.msg);
  });
};

const handleAddForm = (row) => {
  formDeployParam.deployId = row.deploymentId;
  ListFormDeploy();
};

const ListFormDeploy = () => {
  listForm(formQueryParams).then((res) => {
    formList.value = res.rows;
    formTotal.value = res.total;
    formDeployOpen.value = true;
    formDeployTitle.value = "挂载表单";
  });
};

const submitFormDeploy = (row) => {
  formDeployParam.formId = row.formId;
  addDeployForm(formDeployParam).then((res) => {
    ElMessage.success(res.msg);
    formDeployOpen.value = false;
    getList();
  });
};

const handleCurrentChange = (data) => {
  if (data) {
    // 回显数据
    vFormCurrentRowRef.value.setFormJson(JSON.parse(data.formContent));

    vFormCurrentRowRef.value.disableForm();
    // 表单禁用
    // this.$refs.vFormCurrentRowRef.disableForm();
  }
};

const handleUpdateSuspensionState = (row) => {
  let state = 1;
  if (row.suspensionState === 1) {
    state = 2;
  }
  const params = {
    deployId: row.deploymentId,
    state: state,
  };
  updateState(params).then((res) => {
    ElMessage.success(res.msg);
    getList();
  });
};

const handleUpdate = (row) => {
  reset();
  const id = row.deploymentId || ids.value;
  getDeployment(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改流程定义";
  });
};

const submitForm = () => {
  this.$refs["form"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateDeployment(form.value).then((response) => {
          ElMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDeployment(form.value).then((response) => {
          ElMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

const handleDelete = (row) => {
  const deploymentIds = row.deploymentId || ids.value;
  ElMessageBox.confirm(
    '是否确认删除流程定义编号为"' + deploymentIds + '"的数据项?',
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      return delDeployment(deploymentIds);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    });
};

const handleExport = () => {
  const queryParams = this.queryParams;
  ElMessageBox.confirm("是否确认导出所有流程定义数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      return exportDeployment(queryParams);
    })
    .then((response) => {
      // this.download(response.msg); // 需要根据具体实现调整
    });
};

const handleImport = () => {
  upload.title = "bpmn20.xml文件导入";
  upload.open = true;
};

const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  // this.$refs.upload.clearFiles(); // 需要根据具体实现调整
  ElMessage.success(response.msg);
  getList();
};

const submitFileForm = () => {
  // this.$refs.upload.submit(); // 需要根据具体实现调整
};
</script>
<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
